<script>
import { watch, reactive, ref } from "vue";
import Taro from "@tarojs/taro";
import { useOtherInfo } from "./useOtherInfo";
import { useCarCcrn } from "./useCarCcrn";
import { getDicMap } from "@/utils/storage";
import { useTzRouter } from "@/vhooks/useTzRouter";
import { saveOrSubmitUrl } from "./api";
import { getRocarsBundBeanById } from "../api";
import { compareDate, letgetDay } from "@/utils/date";

export default {
  name: "BundleHome",
  components: {},
  setup() {
    const dicMap = getDicMap();
    const state = reactive({
      type: "",
      custompt: "",
      deparrdt: "",
      carInfo: {}, //车辆信息
      isShowCar: false,
      ccrnList: [], //ccrn数据
      goodsList: [], //货物数据
      bundId: "", //捆绑id
    });
    const {
      EventChannel,
      route,
      navigateTo,
      redirectTo,
      navigateBack,
    } = useTzRouter();
    //通过页面地址参数显示是否编辑
    if (route.query.bundId) {
      state.bundId = route.query.bundId;
      const param = { bundId: state.bundId };
      getRocarsBundBeanById(param).then((res) => {
        console.log(res.data);
        initData(res.data);
      });
    }
    /**
     * 监听发送过来的事件
     * eventname: route.path 代表监听当前页面的所有事件
     * event 是发送过来的内容
     */
    EventChannel.on(route.path, (event) => {
      //处理需要的内容名
      if (event?.type === "bundleHomeBack") {
        console.log("接收到", event.data);
        state.carInfo = event.data;
        state.isShowCar = true;
      }
      if (event?.type === "ccrnBack") {
        state.ccrnList = event.data;
      }
      if (event?.type === "goodsBack") {
        //过滤掉跟当前页相同货物的数据
        const filterData = event.data.filter((item) => {
          return !state.goodsIds.includes(item.id);
        });
        state.goodsList = [...state.goodsList, ...filterData];
      }
    });
    if (route) {
      console.log(route);
    }
    const carCcrnHook = useCarCcrn(state, dicMap);
    const otherHook = useOtherInfo(state);

    //编辑捆绑数据数据处理
    const initData = (formData) => {
      //货物数据
      state.goodsList = formData.rocarsBundBean.rocarsList;

      //过滤ccrnList中goodsList有的ccrn号
      const ccrnList = ref(formData.rocarsBundBean.ccrnList);
      state.goodsList.forEach((item) => {
        const padStart = item.ccrn.padStart(11, ","); //‘，’+ccrn号10位
        const padEnd = item.ccrn.padEnd(11, ","); //ccrn号10位+‘，’
        if (ccrnList.value.includes(padStart)) {
          //替换掉【,+ccrn】
          ccrnList.value = ccrnList.value.replace(padStart, "");
        } else if (ccrnList.value.includes(padEnd)) {
          //替换掉【ccrn+,】
          ccrnList.value = ccrnList.value.replace(padEnd, "");
        }
      });
      state.ccrnList = ccrnList.value.split(",");

      //车辆信息
      state.carInfo = {
        hkDriverCode: formData.rocarsBundBean.rocarsId,
        hkTruckLicenseName: formData.rocarsBundBean.vrn,
        driverName: formData.rocarsBundBean.driverName,
        // dMobile: formData.rocarsBundBean.dmobile,
        // hkDMobile: formData.rocarsBundBean.hkDMobile,
      };
      if (formData.rocarsBundBean.type === "I") {
        state.carInfo.dMobile = formData.rocarsBundBean.driverTel;
      } else {
        state.carInfo.hkDMobile = formData.rocarsBundBean.driverTel;
      }

      state.isShowCar = true;
      //进出口类型
      // dicMap.ieTypeList.forEach((item, index) => {
      //   if (item.para_value === formData.rocarsBundBean.type) {
      //     state.typeIndex = index;
      //   }
      // });
      state.type = formData.rocarsBundBean.type;
      //六联单号
      state.docCode = formData.rocarsBundBean.docCode;
      //过关管制站
      // dicMap.passControlList.forEach((item, index) => {
      //   if (item.para_value === formData.rocarsBundBean.custompt) {
      //     state.customptIndex = index;
      //   }
      // });
      state.custompt = formData.rocarsBundBean.custompt;
      //货运日期
      state.deparrdt = formData.rocarsBundBean.deparrdt;
    };

    //校验
    const validateData = (formData) => {
      if (!formData.vrn) {
        Taro.showToast({
          title: "请输入车辆信息",
          icon: "none",
          duration: 2000,
        });
        return false;
      }

      if (!formData.type) {
        Taro.showToast({
          title: "请选择进出口类型",
          icon: "none",
          duration: 2000,
        });
        return false;
      }

      if (
        formData.docCode &&
        !formData.docCode.startsWith("1") &&
        !formData.docCode.startsWith("5") &&
        formData.docCode.length !== 13
      ) {
        Taro.showToast({
          title: "六联单应为1或5开头的13位数字",
          icon: "none",
          duration: 2000,
        });
        return false;
      }

      //进出口I 六联单必须5开头
      //进出口E 六联单必须1开头
      if (
        (formData.type === "I" &&
          formData.docCode &&
          !formData.docCode.startsWith("5")) ||
        (formData.type === "E" &&
          formData.docCode &&
          !formData.docCode.startsWith("1"))
      ) {
        Taro.showToast({
          title: "单据进出口类型与六联单不一致",
          icon: "none",
          duration: 2000,
        });
        return false;
      }

      if (formData.ccrnList.length < 1) {
        Taro.showToast({
          title: "请至少添加一个ccrn码",
          icon: "none",
          duration: 2000,
        });
        return false;
      }

      const arr = Array.from(new Set(formData.ccrnList));
      if (formData.ccrnList.length !== arr.length) {
        Taro.showToast({
          title: "存在相同的ccrn码",
          icon: "none",
          duration: 2000,
        });
        return false;
      }

      if (compareDate(formData.deparrdt, letgetDay(-1))) {
        Taro.showToast({
          title: "货运日期小于当前日期",
          icon: "none",
          duration: 2000,
        });
        return false;
      }
      return true;
    };

    watch(
      () => state.showLoading,
      (val) => {
        if (val) {
          Taro.showLoading({
            title: "加载中",
            icon: "none",
          });
          state.disabledBtn = true;
        } else {
          Taro.hideLoading();
          state.disabledBtn = false;
        }
      }
    );

    //捆绑数据保存
    const saveClick = () => {
      if (state.showLoading) return;
      //进出口类型
      const ieType = state.type;

      const ccrnList = ref([]);
      //货物信息中的ccrn号合并
      state.goodsList.forEach((item) => {
        ccrnList.value.push(item.ccrn);
      });
      //ccrn
      ccrnList.value = [...state.ccrnList, ...ccrnList.value];
      //保存捆绑需要用到的数据
      if (!state.deparrdt) {
        state.deparrdt = letgetDay(0);
      }
      const rocarsBundBean = {
        //apiType: formData.apiType,
        //orderType: orderType,
        //formId: formData.formId, 这3个之前有，现在去掉
        ccrnList: ccrnList.value,
        custompt: state.custompt,
        driverTel:
          ieType === "I" ? state.carInfo.dMobile : state.carInfo.hkDMobile,
        deparrdt: state.deparrdt,
        rocarsId: state.carInfo.hkDriverCode,
        vrn: state.carInfo.hkTruckLicenseName,
        driverName: state.carInfo.driverName,
        docCode: state.docCode,
        type: ieType,
        rocarsList: state.goodsList,
        id: state.bundId,
      };
      if (!validateData(rocarsBundBean)) {
        return false;
      }
      rocarsBundBean.ccrnList = ccrnList.value.join(",");
      state.showLoading = true;
      saveOrSubmitUrl(rocarsBundBean)
        .then((res) => {
          state.showLoading = false;
          if (route.query.bundId) {
            // 从详情页过来
            navigateBack({
              delta: 1,
              event: {
                type: "editBackRefresh", // 编辑页回退
              },
            });
          } else {
            // 新增数据跳转详情
            redirectTo({
              path: "/pages/subHK/bundleInquire/details/index",
              query: { bundId: res.data.rocarsBundId, isNewOrder: 1 },
            });
          }
        })
        .catch(() => {
          state.showLoading = false;
        });
    };
    return () => {
      return (
        <tz-view class="bundle-home">
          {carCcrnHook()}
          {otherHook()}
          <tz-button
            disabled={state.disabledBtn}
            class="save-btn"
            type="primary"
            onClick={saveClick}
          >
            保存
          </tz-button>
        </tz-view>
      );
    };
  },
};
</script>

<style lang="scss">
.bundle-home {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  .section {
    width: 100%;
    background: $white;
    margin-bottom: 10px;
    &:first-child .tz-cell {
      line-height: 60px;
    }
    @extend %bt1;
    .tz-cell:first-child {
      padding: 0 15px;
    }
    .text-right {
      .tz-cell-value {
        flex-direction: row-reverse;
      }
    }
    .car-info {
      display: flex;
      font-size: $font-size-1;
      padding: 6px 0;
      align-items: center;
      @extend %bb1;
      .car-data {
        display: flex;
        flex-direction: column;
        width: 90%;
        font-size: 13px;

        :nth-child(n) {
          height: 24px;
          line-height: 24px;
        }
        .tz-text {
          color: $title-color3;
          width: 110px;
          text-align: right;
          padding-right: 10px;
          display: inline-block;
        }
      }
    }
    .ccrn-info {
      width: 100%;
      background: #f8f8f8;
      display: flex;
      padding: 15px 0 10px 0;
      align-items: center;
      &:nth-child(odd) {
        background-color: $help-color;
      }
      .ccrn-data {
        width: 90%;
        color: $primary-color;
        display: flex;
        align-items: center;
        text {
          width: 100px;
          text-align: right;
          display: inline-block;
          margin-right: 15px;
          font-size: 14px;
          color: $title-color3;
        }
      }
      .orther-data {
        font-size: $font-size-1;
        color: $title-color2;
        .blue {
          text-align: left;
          color: $primary-color;
        }
      }
      .ccrn-del {
        font-size: 14px;
        color: $danger-color;
        margin-right: 10px;
        .tz-icon {
          margin-right: 5px;
        }
      }
    }
  }
  .other-info {
    width: 100%;
    display: flex;
    flex-direction: column;
    @extend %bb1;
    .tz-cell:first-child {
      width: 100%;
      line-height: 50px;
      margin: 0;
    }
    .tz-cell {
      width: calc(100% - 30px);
      margin: 0 15px;
    }
  }
  .ptb5 {
    .fix {
      .tz-input {
        display: inline-block;
        width: 90%;
      }
    }
  }
  .save-btn {
    width: 94%;
    margin: 0 auto;
  }
}
</style>
